/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/index';
import { serialize } from '@/util/util';
import { setRefreshTokenFlag,getToken } from '@/util/store';
import { Message } from 'element-ui';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { setStore, getStore, clearUserSeesion, setToken, getRToken } from '@/util/store'
import { reftoken } from '@/api/user'
axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  // console.log(store.getters.STATE401);
  NProgress.start() // start progress bar
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  const tonkenValue = getToken();
  if (tonkenValue && !isToken) {
    config.headers['Authorization'] = tonkenValue; // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    setRefreshTokenFlag("true");
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  }
  return config;

}, error => {
  return Promise.reject(error)
});



//HTTPresponse拦截
axios.interceptors.response.use(async res => {
  NProgress.done();
  let { config } = res;
  const status = Number(res.status) || 200;
  if (status === 200) {
    return res;
  } else if (status === 401 && res.data.code === 401) {
    await reftokenRreq(config).then((newres)=>{
      res = newres;
    }).catch(err=>{
      store.dispatch('LogOut');//退出登录
    })
    return res;
  } else {
    return res;
    Message({
      message: res.data.message || "网络异常",
      type: 'error'
    })
  }
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
})

export default axios;
//重复执行请求操作
function repeatRequest({ url,method,params }){
  return axios({
    url,
    method,
    params
  })
}
//刷新token 重新加载请求
function reftokenRreq(config) {
  return new Promise((resolve,reject)=>{
    //处理token失效，退出到登录界面
    let r = getRToken();
    //刷新token
    reftoken(r).then(result=>{
      //检测到401中断其他请求
      if(result.data.code == 200 ){
        let token = result.data.data;
        store.commit('SET_TOKEN', token);
        store.commit('DEL_ALL_TAG');
        store.commit('OPEN_LOCK');//将锁打开
        repeatRequest(config).then((newres)=>{
          resolve(newres)
        }).catch(err=>{
          reject()
        })
      }else{
        reject()
      }
    })
  })
}
